//
//  WBComposeViewController.swift
//  WeiBo
//
//  Created by 韩菲菲 on 16/8/17.
//  Copyright © 2016年 韩菲菲. All rights reserved.
//

import UIKit
import SVProgressHUD

class WBComposeViewController: UIViewController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        setupNav()
        
    }
    
    // MARK: - 设置UI
    func setupUI() {
        
        view.backgroundColor = UIColor.whiteColor()
        
        //添加控件
        view.addSubview(customTextView)
        view.addSubview(bottomView)
        customTextView.addSubview(pictureView)
        
        //设置约束
        customTextView.snp_makeConstraints { (make) in
            make.edges.equalTo(view).offset(UIEdgeInsetsZero)
        }
        //设置约束
        bottomView.snp_makeConstraints { (make) in
            make.leading.trailing.bottom.equalTo(view)
            make.height.equalTo(44)
        }
        
        pictureView.snp_makeConstraints { (make) in
            make.top.equalTo(customTextView).offset(100)
            make.size.equalTo(CGSizeMake(ScreenW - 20, ScreenW - 20))
            make.centerX.equalTo(customTextView)
        }
        
        //监听按钮点击
        bottomView.closure = { [weak self](type:WBComposeBottomViewButtonType) in
            switch type{
            case .Picture:
                self?.selectedImage()
            case .Mention:
                print("@被点击")
            case .Trend:
                print("#被点击")
            case .Emoticon:
                self?.switchKeyBoardType()
            case .Add:
                print("添加按钮被点击")
            }
        }
        
        pictureView.closure = {[weak self] in
            
            self?.selectedImage()
        }
        
        //注册通知 监听键盘弹出的通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WBComposeViewController.keyboardWillChangeFrame(_:)), name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        //监听删除按钮点击事件通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WBComposeViewController.deleteBtnClick), name: WBEmoticonKeyBoardDeleteBtnNotification, object: nil)
        
        //监听表情键盘按钮点击事件通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(WBComposeViewController.emoticonBtnClick(_:)), name: WBEmoticonKeyBoardBtnNotification, object: nil)
    }
    
    // MARK: - 自定义键盘删除按钮点击事件的实现
    func deleteBtnClick() {
        
        //删除文字 每次删除一个
        customTextView.deleteBackward()
        
    }
    
    // MARK: - 表情键盘按钮点击事件
    func emoticonBtnClick(notification:NSNotification) {
        
        guard let emoticon = notification.object as? WBEmoticonModel else{
        
            return
        }
        
        //是emoji表情
        if emoticon.isEmoji {
            //把十六进制字符串转换为emoji表情字符串
            let emojiString = (emoticon.code ?? "").emoji()
            //插入
            customTextView.insertText(emojiString)
        }else{
            
            //创建可变富文本 记录当前所有内容
            let allStr = NSMutableAttributedString(attributedString: customTextView.attributedText)
            
           let attr = NSAttributedString.getAttributedStringWithEmoticonModel(emoticon, textSize: 16, y: -4, type: .WBTextType)
            
            //获取当前光标所在的位置 用不可变的富文本来取代
            let selectRange = customTextView.selectedRange
            
            //替换可变富文本
            allStr.replaceCharactersInRange(selectRange, withAttributedString: attr)
            
            //设置可变富文本的font
            allStr.addAttributes([NSFontAttributeName:UIFont.systemFontOfSize(16)], range: NSRange(location: 0, length: allStr.length))
            
            //赋值
            customTextView.attributedText = allStr
            
            //替换光标
            customTextView.selectedRange = NSRange(location: selectRange.location + 1, length: 0)
            
            //手动发送通知 隐藏占位文字
            NSNotificationCenter.defaultCenter().postNotificationName(UITextViewTextDidChangeNotification, object: nil)
            
            //手动执行代理方法  发布按钮可以被点击
            customTextView.delegate?.textViewDidChange!(customTextView)
        
        }
        
        
    }
    
    func keyboardWillChangeFrame(noti:NSNotification){
        
        guard let duration = noti.userInfo?["UIKeyboardAnimationDurationUserInfoKey"] as? Double else{
            return
        }
        
        guard let rect = noti.userInfo?["UIKeyboardFrameEndUserInfoKey"] as? NSValue else{
            return
        }
        
        let newRect = rect.CGRectValue()
        
        //更新约束
        bottomView.snp_updateConstraints { (make) in
            make.bottom.equalTo(view).offset(newRect.origin.y - ScreenH)
        }
        
        UIView.animateWithDuration(duration) {
            //强制刷新UI
            self.view.layer.layoutIfNeeded()
        }
        
    }
    
    // MARK: - 设置导航栏
    func setupNav() {
        
        navigationItem.leftBarButtonItem = UIBarButtonItem(title: "返回", style: .Plain, target: self, action: #selector(WBComposeViewController.cancelAction))
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "发布", style: .Plain, target: self, action: #selector(WBComposeViewController.sendAction))
        
        //按钮不可被点击
        navigationItem.rightBarButtonItem?.enabled = false
        
        //设置自定义titleview
        navigationItem.titleView = customTitleView
    }
    
    // MARK: - 监听事件的实现
    func cancelAction() {
        
        //键盘释放
        customTextView.resignFirstResponder()
        
        //销毁当前控制器
        self.dismissViewControllerAnimated(true, completion: nil)
        
    }
    func sendAction() {
        
        print("发布微博")
        
        //创建可变的字符串
        var str = ""
        
        customTextView.attributedText.enumerateAttributesInRange(NSRange(location: 0,length: customTextView.attributedText.length), options: []) { (result, range, _) in
            
            if let attachment = result["NSAttachment"] as? WBTextAttachment
            {
                //拿到模型中的描述信息
                //拼接
                str += attachment.emoticon?.chs ?? ""
            }else
            {
                //是文字信息
                //截取
                let subStr = (self.customTextView.text as NSString).substringWithRange(range)
                
                str += subStr
            }
        }
        
        
        pictureView.images.count == 0 ? update(str) : upload(str)
        
    }
    
    // MARK: - 懒加载自定义的titleview控件
    private lazy var customTitleView: UILabel = {
        
        //创建label
        let label = UILabel()
        //设置内容
        let name = WBUserAccountViewModel.sharedUserAccountViewModel.userAccount!.screen_name!
        
        let str = "发布微博\n\(name)"
        
        //获取str字符串中的name范围
        let range = (str as NSString).rangeOfString("\(name)")
        
        //创建富文本
        let attribute = NSMutableAttributedString(string: str)
        
        //设置富文本
        attribute.addAttributes([NSForegroundColorAttributeName:AppColor,NSFontAttributeName:UIFont.systemFontOfSize(12)], range: range)
        
        //设置换行
        label.numberOfLines = 0
        
        //设置文字 富文本文字
        label.attributedText = attribute
        
        //文字居中显示
        label.textAlignment = .Center
        
        //设置大小
        label.sizeToFit()
        return label
    }()
    
    // MARK: - 懒加载自定义的textview
    private lazy var customTextView: WBComposeTextView = {
        
        let textView =  WBComposeTextView()
        
        //设置代理  监听有没有文字
        textView.delegate = self
        
        textView.font = UIFont.systemFontOfSize(16)
        
        textView.placeholder = "传智播客传智播客传智播客传智播客传智播客传智播客传智播客传智播客传智播客传智播客"
        
        //允许上下移动
        textView.alwaysBounceVertical = true
        
        
        return textView
    }()
    
    // MARK: - 懒加载图片选择视图
    private lazy var pictureView:WBComposePictureView = WBComposePictureView()
    
    // MARK: - 懒加载底部视图
    private lazy var bottomView:WBComposeBottomView = WBComposeBottomView()
    
    // MARK: - 自定义表情键盘
    private lazy var emoticonKeyboardView:WBEmoticonKeyBoardView = WBEmoticonKeyBoardView(frame:CGRect(x: 0, y: 0, width: ScreenW, height: 216))
    
}

// MARK: - 底部视图按钮点击事件
extension WBComposeViewController{
    
    // bottom视图实现
    func selectedImage() {
        
        //创建UIIMagePickerController
        let vc = UIImagePickerController()
        
        vc.delegate = self
        
        self.presentViewController(vc, animated: true, completion: nil)
        
    }
    //切换键盘
    func switchKeyBoardType() {
        
        //代表当前是系统键盘
        if customTextView.inputView == nil{
            //设置为自定义View
            customTextView.inputView = emoticonKeyboardView
            
            bottomView.isEmoticon = false
            
        }else{
            //代表当前是自定义键盘
            //设置为系统键盘
            customTextView.inputView = nil
            
            bottomView.isEmoticon = true
        }
        
        //刷新
        customTextView.reloadInputViews()
        
        //变为第一相应这
        customTextView.becomeFirstResponder()
        
    }
    
    
}

// MARK: - 发布微博请求
extension WBComposeViewController{
    
    //发布文字微博
    func update(string:String) {
        //customTextView.text
        WBNetworkingTool.sharedTool.updateSina(string, success: { (response) in
            
            //销毁控制器
            self.cancelAction()
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //告诉外界刷新
            NSNotificationCenter.defaultCenter().postNotificationName("updateTableView", object: nil)
            
        }) { (error) in
            
            SVProgressHUD.showErrorWithStatus("发布失败")
        }
    }
    
    //发布图片文字微博
    func upload(string:String) {
        
        WBNetworkingTool.sharedTool.uploadSina(string, images: pictureView.images, success: { (response) in
            
            //销毁控制器
            self.cancelAction()
            
            SVProgressHUD.showSuccessWithStatus("发布成功")
            //告诉外界刷新
            NSNotificationCenter.defaultCenter().postNotificationName("updateTableView", object: nil)
            
            
        }) { (error) in
            
            SVProgressHUD.showErrorWithStatus("发布失败")
            
        }
    
    }
    
}

// MARK: - textView的代理
extension WBComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
    
    func scrollViewDidScroll(scrollView: UIScrollView) {
        self.customTextView.resignFirstResponder()
    }
    
}

// MARK: - UIImagePickController代理实现
extension WBComposeViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate{
    
    //    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
    //        print(image)
    //    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
        
        let image = info["UIImagePickerControllerOriginalImage"] as! UIImage
        
        pictureView.addImage(UIImage.handleImageSize(image, width: 600))
        
 
        picker.dismissViewControllerAnimated(true, completion: nil)
        
    }
    
    
    func imagePickerControllerDidCancel(picker: UIImagePickerController) {
        print("取消按钮被点击了")
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
    
}




